package com.ruoyi.basebill.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.ruoyi.basebill.domain.BomCalcdemand;
import com.ruoyi.basebill.domain.BomCostcalcNewDomain;
import com.ruoyi.basebill.mapper.BillUtilMapper;
import com.ruoyi.basebill.service.IBomCalcdemandService;
import com.ruoyi.basedocument.domain.*;
import com.ruoyi.basedocument.mapper.BomMaterialhalfMapper;
import com.ruoyi.basedocument.service.IBomAsscategoryService;
import com.ruoyi.basedocument.service.IBomCoefficientService;
import com.ruoyi.basedocument.service.IBomSpecialmaterialService;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.PageUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysConfig;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.util.BillUtil;
import com.ruoyi.util.F7RenderingUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.basebill.domain.BomCostcalcentry;
import com.ruoyi.basebill.mapper.BomCostcalcMapper;
import com.ruoyi.basebill.domain.BomCostcalc;
import com.ruoyi.basebill.service.IBomCostcalcService;
import org.springframework.util.CollectionUtils;

/**
 * BOM成本测算Service业务层处理
 * 
 * @author ruoyi
 * @date 2024-09-06
 */
@Service
public class BomCostcalcServiceImpl implements IBomCostcalcService {
    @Autowired
    private BomCostcalcMapper bomCostcalcMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private BomMaterialhalfMapper bomMaterialhalfMapper;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private IBomCalcdemandService bomCalcdemandServiceImpl;
    @Autowired
    private IBomSpecialmaterialService bomSpecialmaterialService;
    @Autowired
    private IBomAsscategoryService bomAsscategoryService;
    @Autowired
    private IBomCoefficientService bomCoefficientService;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private BillUtil billUtil;

    /**
     * 查询BOM成本测算
     * 
     * @param fid BOM成本测算主键
     * @return BOM成本测算
     */
    @Override
    public BomCostcalc selectTBomCostcalcByFid(String fid)
    {
        BomCostcalc bomCostcalc = bomCostcalcMapper.selectBomCostcalcByFid(fid);
        return bomCostcalc;
    }

    /**
     * 查询BOM成本测算列表
     * 
     * @param bomCostcalc BOM成本测算
     * @return BOM成本测算
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<BomCostcalc> selectTBomCostcalcList(BomCostcalc bomCostcalc,boolean isPage) {
        String userCategoryLongCode = "";
        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            userCategoryLongCode = user.getUserCategoryLongCode();
            if(StringUtils.isBlank(userCategoryLongCode)){
                userCategoryLongCode = "(FDescription in ('超级管理员') or FDescription is null)";
            }else{
                userCategoryLongCode = "(FDescription in ('"+userCategoryLongCode.replace(",","','")+"') or FDescription is null)";
            }
            if(SysUser.isAdmin(user.getUserId())){
                userCategoryLongCode = "(FDescription not in ('超级管理员') or FDescription is null)";
            }
        }catch (Exception e){
            System.out.println("获取用户品类失败:"+e);
            userCategoryLongCode = "(FDescription not in ('超级管理员') or FDescription is null)";
        }
        bomCostcalc.setFdescription(userCategoryLongCode);
        String fcreatorid1 = bomCostcalc.getFcreatorid();
        if(StringUtils.isNotBlank(fcreatorid1)){
            SysUser sysUser1 = new SysUser();
            sysUser1.setNickName(fcreatorid1);
            List<SysUser> sysUsers = sysUserService.selectUserList(sysUser1);
            if(sysUsers!=null&&sysUsers.size()!=0){
                String nickName = "(";
                for (int i = 0; i < sysUsers.size(); i++) {
                    nickName += "'"+sysUsers.get(i).getUserName()+"',";
                }
                bomCostcalc.setFcreatorid(nickName.substring(0, nickName.length()-1)+")");
            }
        }
        if(isPage){
            PageUtils.startPage();
        }
        List<BomCostcalc> bomCostcalcs = bomCostcalcMapper.selectBomCostcalcList(bomCostcalc);
        for (int i = 0; i < bomCostcalcs.size(); i++) {
            BomCostcalc bomCostcalc1 = bomCostcalcs.get(i);
            String fcreatorid = bomCostcalc1.getFcreatorid();
            SysUser sysUser = sysUserService.selectUserByUserName(fcreatorid);
            if(sysUser!=null){
                String nickName = sysUser.getNickName();
                bomCostcalc1.setFcreatorid(nickName);
            }
        }
        return bomCostcalcs;
    }

    @Override
    @DataScope(deptAlias = "d")
    public List<BomCostcalcNewDomain> selectBomCostcalcList3(BomCostcalc bomCostcalc) {
        String userCategoryLongCode = "";
        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            userCategoryLongCode = user.getUserCategoryLongCode();
            if(StringUtils.isBlank(userCategoryLongCode)){
                userCategoryLongCode = "(FDescription in ('超级管理员') or FDescription is null)";
            }else{
                userCategoryLongCode = "(FDescription in ('"+userCategoryLongCode.replace(",","','")+"') or FDescription is null)";
            }
            if(SysUser.isAdmin(user.getUserId())){
                userCategoryLongCode = "(FDescription not in ('超级管理员') or FDescription is null)";
            }
        }catch (Exception e){
            System.out.println("获取用户品类失败:"+e);
            userCategoryLongCode = "(FDescription not in ('超级管理员') or FDescription is null)";
        }
        bomCostcalc.setFdescription(userCategoryLongCode);
        String fcreatorid1 = bomCostcalc.getFcreatorid();
        if(StringUtils.isNotBlank(fcreatorid1)){
            SysUser sysUser1 = new SysUser();
            sysUser1.setNickName(fcreatorid1);
            List<SysUser> sysUsers = sysUserService.selectUserList(sysUser1);
            if(sysUsers!=null&&sysUsers.size()!=0){
                String nickName = "(";
                for (int i = 0; i < sysUsers.size(); i++) {
                    nickName += "'"+sysUsers.get(i).getUserName()+"',";
                }
                bomCostcalc.setFcreatorid(nickName.substring(0, nickName.length()-1)+")");
            }
        }
        List<BomCostcalcNewDomain> bomCostcalcNewDomains = bomCostcalcMapper.selectBomCostcalcList3(bomCostcalc);
        return bomCostcalcNewDomains;
//        List<BomCostcalc> bomCostcalcs = bomCostcalcMapper.selectBomCostcalcList(bomCostcalc);
//        String[] strings = new String[bomCostcalcs.size()];
//        for (int i = 0; i < bomCostcalcs.size(); i++) {
//            String number = bomCostcalcs.get(i).getNumber();
//            strings[i] = number;
//        }
//        if (strings.length!=0){
//            List<BomCostcalcNewDomain> bomCostcalcs1 = bomCostcalcMapper.selectBomCostcalcList2(strings);
//            for (int i = 0; i < bomCostcalcs1.size(); i++) {
//                BomCostcalcNewDomain bomCostcalc1 = bomCostcalcs1.get(i);
//                String fcreatorid = bomCostcalc1.getFcreatorid();
//                SysUser sysUser = sysUserService.selectUserByUserName(fcreatorid);
//                if(sysUser!=null){
//                    String nickName = sysUser.getNickName();
//                    bomCostcalc1.setFcreatorid(nickName);
//                }
//            }
//            return bomCostcalcs1;
//        }
//        return new ArrayList<BomCostcalcNewDomain>();
    }

    @Override
    public List<BomCostcalc> selectBomCostcalcListByCalcDemandfids(String[] fids) {
        return bomCostcalcMapper.selectBomCostcalcListByCalcDemandfids(fids);
    }

    @Override
    public BomCostcalc selectBomCostcalcByCalcDemandfid(String fid) {
        BomCostcalc bomCostcalc1 = new BomCostcalc();
        bomCostcalc1.setCfcalcdemandid(fid);
        List<BomCostcalc> bomCostcalcs = bomCostcalcMapper.selectBomCostcalcList(bomCostcalc1);
        if(bomCostcalcs==null||bomCostcalcs.size()==0){
            return null;
        }
        return selectTBomCostcalcByFid(bomCostcalcs.get(0).getFid());
    }

    /**
     * 新增BOM成本测算
     * 
     * @param bomCostcalc BOM成本测算
     * @return 结果
     */
    @Transactional
    @Override
    public int insertTBomCostcalc(BomCostcalc bomCostcalc) {
        String userCategoryLongCode = "";
        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            userCategoryLongCode = user.getUserCategoryLongCode();
            if(StringUtils.isBlank(userCategoryLongCode)){
                userCategoryLongCode = "";
            }else{
                userCategoryLongCode = "'"+userCategoryLongCode.replace(",","','")+"'";
            }
            if(SysUser.isAdmin(user.getUserId())){
                userCategoryLongCode = "'超级管理员'";
            }
        }catch (Exception e){
            System.out.println("获取用户品类失败:"+e);
            userCategoryLongCode = "";
        }
        String fdescription = bomCostcalc.getFdescription();
        if (StringUtils.isBlank(fdescription)) {
            fdescription = "";
        }
        String add2 = "'"+ fdescription.replace(",","','")+"'";
        if(!"'超级管理员'".equals(userCategoryLongCode)&&!userCategoryLongCode.contains(add2)){
            throw new RuntimeException("没有操作该品类的权限，请修改品类或联系管理员添加权限");
        }
        //判断据编号是否存在
        String billNumber = billUtil.createBillNumber("CBCS", "t_bom_costcalc");
        bomCostcalc.setNumber(billNumber);
        String username = SecurityUtils.getLoginUser().getUsername();
        bomCostcalc.setFcreatetime(DateUtils.getNowDate());
        bomCostcalc.setFcreatorid(username);
        bomCostcalc.setCreateBy(username);
        bomCostcalc.setCreateTime(DateUtils.getNowDate());
        setDeptIdByNumber(bomCostcalc);
        int rows = bomCostcalcMapper.insertBomCostcalc(bomCostcalc);
        insertBomCostcalcentry(bomCostcalc);
        return rows;
    }
    @Transactional
    @Override
    public int batchBomCostcalc(List<BomCostcalc> bomCostcalcList){
        for (BomCostcalc bomCostcalc : bomCostcalcList) {
            //获取当前登陆人姓名
            String username = SecurityUtils.getLoginUser().getUsername();
            bomCostcalc.setFcreatetime(DateUtils.getNowDate());
            bomCostcalc.setFcreatorid(username);
            bomCostcalc.setCreateBy(username);
            bomCostcalc.setCreateTime(DateUtils.getNowDate());
        }
        int rows = bomCostcalcMapper.batchBomCostcalc(bomCostcalcList);
        batchBomCostcalcentry(bomCostcalcList);
        return rows;
    }

    /**
     * 修改BOM成本测算
     * 
     * @param bomCostcalc BOM成本测算
     * @return 结果
     */
    @Transactional
    @Override
    public int updateTBomCostcalc(BomCostcalc bomCostcalc) {
        String userCategoryLongCode = "";
        try {
            SysUser user = SecurityUtils.getLoginUser().getUser();
            userCategoryLongCode = user.getUserCategoryLongCode();
            if(StringUtils.isBlank(userCategoryLongCode)){
                userCategoryLongCode = "";
            }else{
                userCategoryLongCode = "'"+userCategoryLongCode.replace(",","','")+"'";
            }
            if(SysUser.isAdmin(user.getUserId())){
                userCategoryLongCode = "'超级管理员'";
            }
        }catch (Exception e){
            System.out.println("获取用户品类失败:"+e);
            userCategoryLongCode = "";
        }
        String fdescription = bomCostcalc.getFdescription();
        if (StringUtils.isBlank(fdescription)) {
            fdescription = "";
        }
        String add2 = "'"+ fdescription.replace(",","','")+"'";
        if(!"'超级管理员'".equals(userCategoryLongCode)&&!userCategoryLongCode.contains(add2)){
            throw new RuntimeException("没有操作该品类的权限，请修改品类或联系管理员添加权限");
        }
        String username = SecurityUtils.getUsername();
        Date nowDate = DateUtils.getNowDate();
        bomCostcalc.setFlastupdateuserid(username);
        bomCostcalc.setFlastupdatetime(nowDate);
        bomCostcalc.setUpdateBy(username);
        bomCostcalc.setUpdateTime(nowDate);
        setDeptIdByNumber(bomCostcalc);
        bomCostcalcMapper.deleteBomCostcalcentryByFParentID(bomCostcalc.getFid());
        insertBomCostcalcentry(bomCostcalc);
        return bomCostcalcMapper.updateBomCostcalc(bomCostcalc);
    }

    private void setDeptIdByNumber(BomCostcalc bomCostcalc){
        String fsourcefunction = bomCostcalc.getFsourcefunction();
        SysDept sysDept = new SysDept();
        sysDept.setDeptNumber(fsourcefunction);
        List<SysDept> sysDepts = sysDeptService.selectDeptList2(sysDept);
        if (sysDepts==null||sysDepts.size()==0) {
            throw new RuntimeException("部门状态异常，请调整部门:"+fsourcefunction);
        }
        bomCostcalc.setDeptName(sysDepts.get(0).getDeptName());
        bomCostcalc.setDeptId(sysDepts.get(0).getDeptId());
    }
    /**
     * 批量删除BOM成本测算
     * 
     * @param fids 需要删除的BOM成本测算主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTBomCostcalcByFids(String[] fids) {
        bomCostcalcMapper.deleteBomCostcalcentryByFParentIDs(fids);
        return bomCostcalcMapper.deleteBomCostcalcByFids(fids);
    }

    /**
     * 删除BOM成本测算信息
     * 
     * @param fid BOM成本测算主键
     * @return 结果
     */
    @Transactional
    @Override
    public int deleteTBomCostcalcByFid(String fid) {
        bomCostcalcMapper.deleteBomCostcalcentryByFParentID(fid);
        return bomCostcalcMapper.deleteBomCostcalcByFid(fid);
    }

    /**
     * 新增成本测算分录信息
     * 
     * @param bomCostcalc BOM成本测算对象
     */
    public void insertBomCostcalcentry(BomCostcalc bomCostcalc) {
        if (bomCostcalc!=null) {
            List<BomCostcalcentry> bomCostcalcentryList = bomCostcalc.getBomCostcalcentryList();
            String fid = bomCostcalc.getFid();
            if (StringUtils.isNotNull(bomCostcalcentryList)) {
                List<BomCostcalcentry> list = new ArrayList<BomCostcalcentry>();
                for (BomCostcalcentry bomCostcalcentry : bomCostcalcentryList) {
                    bomCostcalcentry.setFparentid(fid);
                    list.add(bomCostcalcentry);
                }
                if (list.size() > 0) {
                    bomCostcalcMapper.batchBomCostcalcentry(list);
                }
            }
        }
    }

    public void batchBomCostcalcentry(List<BomCostcalc> bomCostcalcList) {
        List<BomCostcalcentry> list = new ArrayList<BomCostcalcentry>();
        for (BomCostcalc bomCostcalc : bomCostcalcList) {
            if (bomCostcalc!=null) {
                List<BomCostcalcentry> bomCostcalcentryList = bomCostcalc.getBomCostcalcentryList();
                String fid = bomCostcalc.getFid();
                if (StringUtils.isNotNull(bomCostcalcentryList)) {
                    for (BomCostcalcentry bomCostcalcentry : bomCostcalcentryList) {
                        bomCostcalcentry.setFparentid(fid);
                        list.add(bomCostcalcentry);
                    }
                }
            }
        }
        if (list.size() > 0) {
            bomCostcalcMapper.batchBomCostcalcentry(list);
        }
    }
    @Override
    public HashMap getMaterialBomAllNodes(String id,String longCode1){
        SysConfig sysConfig = sysConfigService.selectConfigByConfigKey("BomLevel");
        String BomLevel;
        if(sysConfig!=null){
            BomLevel = sysConfig.getConfigValue();
        }else{
            BomLevel = "10000";
        }
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("list",null);
        //物料编码+长编码
        HashMap<String, String> hashMap2 = new HashMap<>();
        //物料编码+用量
        HashMap<String, BigDecimal> hashMap3 = new HashMap<>();
        //长编码+物料编码
        HashMap<String, String> hashMap4 = new HashMap<>();
        ArrayList<BomMaterialhalfentry> bomMaterialhalfentries = new ArrayList<>();
        //物料编码
        ArrayList<String> numbers = new ArrayList<>();
        //长编码
        ArrayList<String> longCodes = new ArrayList<>();
        BomMaterialhalf bomMaterialhalf = bomMaterialhalfMapper.selectBomMaterialhalfByFid(id);
        String paramNumber = bomMaterialhalf.getCfmaterialnumber();
        hashMap2.put(paramNumber,longCode1);
        hashMap4.put(longCode1,paramNumber);
        hashMap3.put(longCode1,BigDecimal.ONE);
        paramNumber = longCode1;
        if (bomMaterialhalf != null) {
            List<BomMaterialhalfentry> bomMaterialhalfentryList = bomMaterialhalf.getBomMaterialhalfentryList();
            while (true) {
                if(hashMap.containsKey("reason")){
                    break;
                }
                String longCode = "";
                if(bomMaterialhalfentryList==null){
                    if(longCodes.size()==0){
                        break;
                    }else if(longCodes.size()>Integer.parseInt(BomLevel)||bomMaterialhalfentries.size()>Integer.parseInt(BomLevel)){
                        hashMap.put("reason","查询的下级物料超过"+Integer.parseInt(BomLevel)+"条！请确定BOM中的层级是否正常，若正常，请联系管理员放宽限制");
                        return hashMap;
                    }
                    longCode = longCodes.get(0);
                    paramNumber = hashMap4.get(longCode);
                    longCodes.remove(0);
                    BomMaterialhalf bomMaterialhalf1 = new BomMaterialhalf();
                    bomMaterialhalf1.setCfmaterialnumber(paramNumber);
                    List<BomMaterialhalf> bomMaterialhalves = bomMaterialhalfMapper.selectBomMaterialhalfList2(bomMaterialhalf1);
                    if(bomMaterialhalves!=null&&bomMaterialhalves.size()!=0){
                        paramNumber = longCode;
                        BomMaterialhalf bomMaterialhalf2 = bomMaterialhalfMapper.selectBomMaterialhalfByFid(bomMaterialhalves.get(0).getFid());
                        BigDecimal bigDecimal = hashMap3.get(longCode);
                        BigDecimal cfproductionquantity = bomMaterialhalf2.getCfproductionquantity();
                        hashMap3.put(longCode,bigDecimal.divide(cfproductionquantity, 10, RoundingMode.HALF_UP));
                        bomMaterialhalfentryList = bomMaterialhalf2.getBomMaterialhalfentryList();
                    }
                }
                for (int i = 0; bomMaterialhalfentryList!=null&&i < bomMaterialhalfentryList.size(); i++) {
                    BigDecimal bigDecimal = hashMap3.get(paramNumber);
                    String time = new Date().getTime()+""+i;
                    BomMaterialhalfentry bomMaterialhalfentry = bomMaterialhalfentryList.get(i);
//                    String paramNumber1 = hashMap2.get(paramNumber);
                    String longCode2 = null;
                    if(longCode.length()==0){
                        bomMaterialhalfentry.setParamnumber(longCode1);
                        longCode2 = longCode1 + "," + time;
                    }else{
                        bomMaterialhalfentry.setParamnumber(longCode);
                        longCode2 = longCode1 + "," + time;
                    }
                    bomMaterialhalfentry.setLongCode(longCode2);
                    if(bomMaterialhalfentry.getCfconsumption().compareTo(BigDecimal.ZERO)>0){
                        bomMaterialhalfentry.setCfconsumption(bomMaterialhalfentry.getCfconsumption().multiply(bigDecimal));
                    }
                    bomMaterialhalfentries.add(bomMaterialhalfentry);
                    hashMap2.put(bomMaterialhalfentry.getCfrawmaterialnumbe(),longCode2);
                    hashMap4.put(longCode2,bomMaterialhalfentry.getCfrawmaterialnumbe());
                    hashMap3.put(longCode2,bomMaterialhalfentry.getCfconsumption());
//                    hashMap3.put(bomMaterialhalfentry.getCfrawmaterialnumbe(),bomMaterialhalfentry.getCfconsumption());
                    numbers.add(0,bomMaterialhalfentry.getCfrawmaterialnumbe());
                    longCodes.add(0,longCode2);
                }
                bomMaterialhalfentryList = null;
                hashMap.put("list",bomMaterialhalfentries);
            }
        }
        ArrayList<BomMaterialhalfentry> list = (ArrayList<BomMaterialhalfentry>)hashMap.get("list");
        if(list!=null&&list.size()!=0){
            for (int i = 0; i < list.size(); i++) {
                BomMaterialhalfentry bomMaterialhalfentry = list.get(i);
                BomSpecialmaterial bomSpecialmaterial = new BomSpecialmaterial();
                bomSpecialmaterial.setMaterialnumber(bomMaterialhalfentry.getCfrawmaterialnumbe());
                List<BomSpecialmaterial> bomSpecialmaterials = bomSpecialmaterialService.selectBomSpecialmaterialList2(bomSpecialmaterial);
                if (bomSpecialmaterials!=null&&bomSpecialmaterials.size()!=0) {
                    bomMaterialhalfentry.setCftaxrate(bomSpecialmaterials.get(0).getTaxrate());
                }
            }
            Collections.sort(list, Comparator.comparing(BomMaterialhalfentry::getCfrawmaterialnumbe));
        }
        return hashMap;
    }

    /**
     * 单据状态操作
     *
     * @param ids 主键
     * @return 结果
     */
    public HashMap optionStatus(String[] ids, String status) {
        HashMap<String, ArrayList> hashMap = new HashMap<>();
        ArrayList<String> arr = new ArrayList<>();
        hashMap.put("data", arr);
        if("SUBMIT".equals(status)){
            for (int i = 0; i < ids.length; i++) {
                BomCostcalc bomCostcalc = bomCostcalcMapper.selectBomCostcalcByFid(ids[i]);
                if (bomCostcalc==null) {
                    ArrayList<String> data = hashMap.get("data");
                    data.add(bomCostcalc.getNumber());
                    hashMap.put("data",data);
                    continue;
                }
                List<BomCostcalcentry> bomCostcalcentryList = bomCostcalc.getBomCostcalcentryList();
                List<BomCostcalcentry> CostEntries = getCostEntries(bomCostcalcentryList);
                if(bomCostcalcentryList ==null||bomCostcalcentryList.size()==0){
                    ArrayList<String> data = hashMap.get("data");
                    data.add(bomCostcalc.getNumber());
                    hashMap.put("data",data);
                    continue;
                }
                boolean isintroductionRawPrice = true;
                for (int i1 = 0; i1 < bomCostcalcentryList.size(); i1++) {
                    BomCostcalcentry bomCostcalcentry = bomCostcalcentryList.get(i1);
//                    BigDecimal cftaxprice = bomCostcalcentry.getCftaxprice();
//                    if(cftaxprice==null||BigDecimal.ZERO.compareTo(cftaxprice)==0){
//                        isintroductionRawPrice = false;
//                        ArrayList<String> data = hashMap.get("data");
//                        data.add(bomCostcalc.getNumber());
//                        hashMap.put("data",data);
//                        break;
//                    }
                    String cfbomcostcalcnumbe = bomCostcalcentry.getCfbomcostcalcnumbe();
                    String cfbomcostcalcentryid = bomCostcalcentry.getCfbomcostcalcentryid();
                    String cfrawmaterialid = bomCostcalcentry.getCfrawmaterialid();
                    String cfcategoryname = bomCostcalcentry.getCfcategoryname();
                    if("2".equals(cfbomcostcalcnumbe)&&!cfbomcostcalcentryid.contains(",")
                            &&StringUtils.isNotBlank(cfrawmaterialid)&&"50".equals(cfrawmaterialid.substring(0,2))
                                &&StringUtils.isBlank(cfcategoryname)){
                        isintroductionRawPrice = false;
                        ArrayList<String> data = hashMap.get("data");
                        data.add(bomCostcalc.getNumber());
                        hashMap.put("data",data);
                        break;
                    }
                }
                for (int i1 = 0; CostEntries!=null&&i1 < CostEntries.size(); i1++) {
                    BomCostcalcentry bomCostcalcentry = CostEntries.get(i1);
                    String cfcategoryname = bomCostcalcentry.getCfcategoryname();
                    if(StringUtils.isBlank(cfcategoryname)){
                        isintroductionRawPrice = false;
                        ArrayList<String> data = hashMap.get("data");
                        data.add(bomCostcalc.getNumber());
                        hashMap.put("data",data);
                        break;
                    }
                }
                if(isintroductionRawPrice){
                    bomCostcalc.setCfstate(status);
                    bomCostcalcMapper.updateBomCostcalc(bomCostcalc);
                }
            }
            return hashMap;
        }
        for (int i = 0; i < ids.length; i++) {
            BomCostcalc bomCostcalc = selectTBomCostcalcByFid(ids[i]);
            bomCostcalc.setCfstate(status);
            bomCostcalcMapper.updateBomCostcalc(bomCostcalc);
        }
        return hashMap;
    }

    /**
     * 移交产品库
     *
     * @param id 主键
     * @return 结果
     */
    public void moveProdect(String id, boolean isMove) {
        BomCostcalc bomCostcalc = selectTBomCostcalcByFid(id);
        if(isMove){
            bomCostcalc.setFfivouchered(1L);
        }else{
            bomCostcalc.setFfivouchered(0L);
        }
        bomCostcalcMapper.updateBomCostcalc(bomCostcalc);
    }

    /**
     * 反写测算需求
     *
     * @param ids 主键
     * @return 结果
     */
    public void reverse(String[] ids) {
        for (int i = 0; i < ids.length; i++) {
            BomCalcdemand bomCalcdemand = bomCalcdemandServiceImpl.selectBomCalcdemandByFid(ids[i]);
            if(bomCalcdemand!=null){
                bomCalcdemand.setIspush("0");
                bomCalcdemandServiceImpl.updateBomCalcdemand(bomCalcdemand);
            }
        }
    }

    /**
     * 查询成本测算分录
     *
     * @param fid 成本测算分录主键
     * @return 成本测算分录
     */
    @Override
    public BomCostcalcentry selectBomCostcalcentryByFid(String fid)
    {
        return bomCostcalcMapper.selectBomCostcalcentryByFid(fid);
    }

    public BomCostcalcentry removeEntry(BomCostcalcentry entry,boolean isClearMaterial,boolean isClearPrice,boolean isClearCategory){
        if(isClearMaterial){
            entry.setCfmaterialhalfnumb(null);
            entry.setCfmaterialhalfname(null);
            entry.setCfmaterialhalfunit(null);
        }
        if(isClearPrice){
            entry.setCftaxrate(BigDecimal.ZERO);
            entry.setCftaxprice(BigDecimal.ZERO);
            entry.setCfdeduction(BigDecimal.ZERO);
        }
        if(isClearCategory){
            entry.setCfcategoryname(null);
            entry.setCfcategoryid(null);
            entry.setCfworkshopname(null);
        }
        entry.setCfrgbd(BigDecimal.ZERO);
        entry.setCfrggd(BigDecimal.ZERO);
        entry.setCfsbd(BigDecimal.ZERO);
        entry.setCfsgd(BigDecimal.ZERO);
        entry.setCfdbd(BigDecimal.ZERO);
        entry.setCfdgd(BigDecimal.ZERO);
        entry.setCfqbd(BigDecimal.ZERO);
        entry.setCfqgd(BigDecimal.ZERO);
        entry.setCfzjbd(BigDecimal.ZERO);
        entry.setCfzjgd(BigDecimal.ZERO);
        entry.setCfqtbd(BigDecimal.ZERO);
        entry.setCfqtgd(BigDecimal.ZERO);
        entry.setCfede(BigDecimal.ZERO);
        entry.setCfrgbdxj(BigDecimal.ZERO);
        entry.setCfrggdxj(BigDecimal.ZERO);
        entry.setCfsbdxj(BigDecimal.ZERO);
        entry.setCfsgdxj(BigDecimal.ZERO);
        entry.setCfdbdxj(BigDecimal.ZERO);
        entry.setCfdgdxj(BigDecimal.ZERO);
        entry.setCfqbdxj(BigDecimal.ZERO);
        entry.setCfqgdxj(BigDecimal.ZERO);
        entry.setCfzjbdxj(BigDecimal.ZERO);
        entry.setCfzjgdxj(BigDecimal.ZERO);
        entry.setCfqtbdxj(BigDecimal.ZERO);
        entry.setCfqtgdxj(BigDecimal.ZERO);
        entry.setCfedexj(BigDecimal.ZERO);
        entry.setCfnotaxsum(BigDecimal.ZERO);
        entry.setCfchangefee(BigDecimal.ZERO);
        entry.setCffixationfee(BigDecimal.ZERO);
        return entry;
    }

    /**
     * 查询系数
     *
     * @param bomCostcalc BOM成本测算
     * @return 结果
     */
    @Transactional
    @Override
    public HashMap getBomCoffe(BomCostcalc bomCostcalc) {
        HashMap<String, List<BomCostcalcentry>> stringListHashMap = new HashMap<>();
        stringListHashMap.put("list",null);
        String longCode = bomCostcalc.getLongCode();
        String[] split = longCode.split(",");
        String cfwfzbaseid = bomCostcalc.getCfwfzbaseid();
        String cfseasontypeid = bomCostcalc.getCfseasontypeid();
        if (bomCostcalc!=null) {
            List<BomCostcalcentry> bomCostcalcentryList = bomCostcalc.getBomCostcalcentryList();
            for (int iq = 0; iq < split.length; iq++) {
                String s = split[iq];
                longCode = s;
                if(StringUtils.isNotBlank(s)){
                    for (int i = 0; i < bomCostcalcentryList.size(); i++) {
                        BomCostcalcentry bomCostcalcentry = bomCostcalcentryList.get(i);
                        //判断当前分录是否是要查询系数的分录
                        if(bomCostcalcentry.getCfbomcostcalcentryid()!=null&&bomCostcalcentry.getCfbomcostcalcentryid().contains(longCode)){
                            String cfmaterialhalfnumb = bomCostcalcentry.getCfmaterialhalfnumb();
                            //判断是否有物料编码
                            if(StringUtils.isNotEmpty(cfmaterialhalfnumb)){
                                BomSpecialmaterial bomSpecialmaterial = new BomSpecialmaterial();
                                bomSpecialmaterial.setMaterialnumber(cfmaterialhalfnumb);
                                List<BomSpecialmaterial> bomSpecialmaterials = bomSpecialmaterialService.selectBomSpecialmaterialList2(bomSpecialmaterial);
                                //是否存在特殊物料
                                if (bomSpecialmaterials!=null&&bomSpecialmaterials.size()!=0) {
                                    BomSpecialmaterial bomSpecialmaterial1 = bomSpecialmaterials.get(0);
                                    bomCostcalcentry.setCfrawmaterialid(bomSpecialmaterial1.getGroup4number());
                                    bomCostcalcentry.setCftaxrate(bomSpecialmaterial1.getTaxrate());
                                    BomAsscategory bomAsscategory = new BomAsscategory();
                                    bomAsscategory.setMaterialbomnumber(cfmaterialhalfnumb);
                                    List<BomAsscategory> bomAsscategories = bomAsscategoryService.selectBomAsscategoryList2(bomAsscategory);
                                    //BOM类别关联
                                    if (bomAsscategories!=null&&bomAsscategories.size()!=0) {
                                        String categoryid = bomAsscategories.get(0).getCategoryid();
                                        String categoryname = bomAsscategories.get(0).getCategoryname();
                                        String categorynumber = bomAsscategories.get(0).getCategorynumber();
                                        String cfplantid = bomAsscategories.get(0).getCfplantid();
                                        bomCostcalcentry.setCfcategoryid(categoryid);
                                        bomCostcalcentry.setCfcategoryname(categoryname);
                                        bomCostcalcentry.setCfworkshopname(cfplantid);
                                        //存在基地+时间类型+类别
                                        if(StringUtils.isNotEmpty(cfwfzbaseid)&&StringUtils.isNotEmpty(cfseasontypeid)&&StringUtils.isNotEmpty(categorynumber)){
                                            BomCoefficient bomCoefficient = new BomCoefficient();
                                            bomCoefficient.setCfisnew(1L);
                                            bomCoefficient.setFnumber(categorynumber);
                                            bomCoefficient.setCfwfzbaseid(cfwfzbaseid);
                                            bomCoefficient.setCfseasontypeid(cfseasontypeid);
                                            List<BomCoefficient> bomCoefficients = bomCoefficientService.selectBomCoefficientList(bomCoefficient);
                                            //存在系数
                                            if (bomCoefficients!=null&&bomCoefficients.size()!=0) {
                                                BomCoefficient bomCoefficient1 = bomCoefficients.get(0);
                                                bomCostcalcentry.setCfrgbd(bomCoefficient1.getCfrgbd());
                                                bomCostcalcentry.setCfrggd(bomCoefficient1.getCfrggd());
                                                bomCostcalcentry.setCfsbd(bomCoefficient1.getCfsbd());
                                                bomCostcalcentry.setCfsgd(bomCoefficient1.getCfsgd());
                                                bomCostcalcentry.setCfdbd(bomCoefficient1.getCfdbd());
                                                bomCostcalcentry.setCfdgd(bomCoefficient1.getCfdgd());
                                                bomCostcalcentry.setCfqbd(bomCoefficient1.getCfqbd());
                                                bomCostcalcentry.setCfqgd(bomCoefficient1.getCfqgd());
                                                bomCostcalcentry.setCfzjbd(bomCoefficient1.getCfzjbd());
                                                bomCostcalcentry.setCfzjgd(bomCoefficient1.getCfzjgd());
                                                bomCostcalcentry.setCfqtbd(bomCoefficient1.getCfqtbd());
                                                bomCostcalcentry.setCfqtgd(bomCoefficient1.getCfqtgd());
                                                bomCostcalcentry.setCfede(bomCoefficient1.getCfede());
                                            }
                                            else{
                                                removeEntry(bomCostcalcentry,false,false,false);
                                            }
                                        }
                                        else{
                                            removeEntry(bomCostcalcentry,false,false,false);
                                        }
                                    }
                                    else{
                                        removeEntry(bomCostcalcentry,false,false,true);
                                    }
                                }
                                else{
                                    removeEntry(bomCostcalcentry,true,true,true);
                                }
                            }
                            else{
                                removeEntry(bomCostcalcentry,true,true,true);
                            }
                        }
                    }
                    stringListHashMap.put("list",bomCostcalcentryList);
                }
            }
        }
        return stringListHashMap;
    }

    //获取原材料分录
    public List<BomCostcalcentry> getRawMaterialEntries(List<BomCostcalcentry> nodes) {
        Set<String> allIndices = new HashSet<>();
        Set<String> parentIndices = new HashSet<>();
        for (BomCostcalcentry node : nodes) {
            allIndices.add(node.getCfbomcostcalcentryid());
            if (StringUtils.isNotEmpty(node.getCfrawmaterialnumbe())) {
                parentIndices.add(node.getCfrawmaterialnumbe());
            }
        }
        allIndices.removeAll(parentIndices);
        List<BomCostcalcentry> collect = nodes.stream().filter(
                n -> allIndices != null && allIndices.size() > 0 && allIndices.contains(n.getCfbomcostcalcentryid())).collect(Collectors.toList());
        return collect;
    }

    //获取费用分录
    public List<BomCostcalcentry> getCostEntries(List<BomCostcalcentry> nodes) {
        Set<String> parentIndices = new HashSet<>();
        for (BomCostcalcentry node : nodes) {
            if (StringUtils.isNotEmpty(node.getCfrawmaterialnumbe())) {
                parentIndices.add(node.getCfrawmaterialnumbe());
            }
            if(!node.getCfbomcostcalcentryid().contains(",")&&"2".equals(node.getCfbomcostcalcnumbe())){
                parentIndices.add(node.getCfrawmaterialnumbe());
            }
        }
        List<BomCostcalcentry> collect = nodes.stream().filter(
                n -> parentIndices != null && parentIndices.size() > 0 && parentIndices.contains(n.getCfbomcostcalcentryid())).collect(Collectors.toList());
        return collect;
    }
}
